package com.example.myapplication;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class RecyclerActivity extends AppCompatActivity {
    private RecyclerView mRecycler;
    private FruitAdapter mAdapter;

    private LayoutInflater mLayoutInflater;//layout的加载工具

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler);
        init();
    }

    private void init() {
        mRecycler = findViewById(R.id.recycler_view);
        mAdapter = new FruitAdapter();
        mLayoutInflater =  getLayoutInflater();
        LinearLayoutManager manager = new LinearLayoutManager(this);

        mRecycler.setAdapter(mAdapter);
        mRecycler.setLayoutManager(manager);

        loadData();

    }

    private void loadData() {
        String[] data = { "Apple", "Banana", "Orange", "Watermelon",
                "Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango",
                "Apple", "Banana", "Orange", "Watermelon", "Pear", "Grape",
                "Pineapple", "Strawberry", "Cherry", "Mango" };

        List<Fruit> rows=new ArrayList<>();
        for(String name:data){//name可以换成其它的
            rows.add(new Fruit(name,Math.random() * 100));
        }

        mAdapter.addData(rows);
    }

    private static class FruitViewHolder extends RecyclerView.ViewHolder{

        TextView name;
        TextView price;


        public FruitViewHolder(@NonNull View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.name);
            price = itemView.findViewById(R.id.price);
        }
    }

    private class FruitAdapter extends RecyclerView.Adapter<FruitViewHolder> {

        private List<Fruit> data = new ArrayList<>();

        @NonNull
        @Override
        public FruitViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view =  mLayoutInflater.inflate(R.layout.item_recycler,parent,false);
            return new FruitViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull FruitViewHolder holder, int position) {
            Fruit item = data.get(position);
            holder.name.setText( item.name );
            holder.price.setText( item.price + "");
        }

        @Override
        public int getItemCount() {
            return data.size();
        }

        public void addData(List<Fruit> rows) {
            data.addAll(rows);
            this.notifyDataSetChanged();
        }
    }
}
